const app = getApp();
var pageNo = 1;
var pageSize = 10;
var jielongPageNo = 1;
var jielongPageSize = 10;
var url = app.data.url;
var common = require('../../utils/common.js');
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    order: [],
    selectOrderPopup: false,
    unSubscribeOrderPopup: false,
    itemInfoList: [],
    activeNames: ['1'],
    preNum: '',
    title: "",
    modelId: '4sLRplyItbyfh7G6eD87LcXqe7cidohH8vOdc7uwhQU',
    merchantId: '',
    item: [],
    tabActive: 0, //默认显示第一个tab
    isTabOneInit:false,
    isTabTwoInit:false
  },
  tabOnClick: function(event){
    //event.detail.name
    var that = this;
    console.info(that.data.tabActive);
    if (event.detail.title == "接龙订单"){
      that.setData({
        tabActive: 1
      });
      if (!that.data.isTabTwoInit){
        that.queryTable(jielongPageNo, jielongPageSize, app.globalData.openId, that.data.isTabTwoInit, "Y");
      }
      
    } else {
      that.setData({
        tabActive: 0
      });
    }
  },
  closeUnSbPopup: function() {
    this.setData({
      unSubscribeOrderPopup: false
    });
  },
  openUnSbPopup: function(option) {
    let item = option.currentTarget.dataset.item;
    item.isJielong = option.currentTarget.dataset.isjielong;
    let json = JSON.stringify(item);
    console.info(item);
    this.setData({
      unSubscribeOrderPopup: true,
      item: json
    });
  },
  pay: function(options) {
    let that = this;
    let uuid = options.currentTarget.dataset.wxuseruuid;
    let orderId = options.currentTarget.dataset.orderid;
    let merchantId = options.currentTarget.dataset.merchantid;

    // 先查询有无默认联系人和手机号
    wx.request({
      url: url + '/CommonRelationApi/queryCommonRelationByUuid',
      data: {
        uuid: uuid
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          let item = res.data.data;
          let name = item.name;
          let phone = item.phone;
          // 有查询出名字和手机, 更新当前订单联系人和手机
          wx.request({
            url: url + '/OrderApi/updateNameAndPhoneByOrderId',
            data: {
              orderId: orderId,
              name: name,
              phone: phone
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
              if (res.data.code == 200) {
                wx.requestSubscribeMessage({
                  tmplIds: [that.data.modelId],
                  success(res) {
                    wx.request({
                      url: url + '/WeChatPayApi/servicePrePay',
                      data: {
                        uuid: uuid,
                        orderId: orderId,
                        merchantId: merchantId
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      success: function(res) {
                        if (res.data.code == 200) {
                          let item = res.data.data;
                          let wxPaymentPojo = item.wxPaymentParamPojo;
                          // 发起支付
                          wx.requestPayment({
                            'timeStamp': wxPaymentPojo.timeStamp,
                            'nonceStr': wxPaymentPojo.nonceStr,
                            'package': wxPaymentPojo.packageStr,
                            'signType': 'MD5',
                            'paySign': wxPaymentPojo.paySign,
                            'success': function(res) {
                              console.log("支付成功！！！！！");
                              // 支付成功, 新增一条支付单记录
                              let jsonParam = JSON.stringify(item.stringStringMap);
                              wx.request({
                                url: url + '/WeChatPayApi/insertWxPay',
                                data: {
                                  jsonParam: jsonParam
                                },
                                method: 'POST',
                                header: {
                                  'content-type': 'application/x-www-form-urlencoded'
                                },
                                success: function(res) {
                                  if (res.data.code == 200) {
                                    // 重新加载订单列表
                                    wx.request({
                                      url: url + '/OrderApi/listPageOrder',
                                      data: {
                                        pageNo: pageNo,
                                        pageSize: pageSize,
                                        createUserName: app.globalData.openId
                                      },
                                      method: 'POST',
                                      header: {
                                        'content-type': 'application/x-www-form-urlencoded'
                                      },
                                      success: function(res) {
                                        if (res.data.code == 200) {
                                          // 支付成功, 更新订单状态
                                          wx.request({
                                            url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                            data: {
                                              orderId: options.currentTarget.dataset.orderid
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function(res) {
                                              if (res.data.code == 200) {
                                                // 重新加载订单列表
                                                wx.request({
                                                  url: url + '/OrderApi/listPageOrder',
                                                  data: {
                                                    pageNo: pageNo,
                                                    pageSize: pageSize,
                                                    createUserName: app.globalData.openId
                                                  },
                                                  method: 'POST',
                                                  header: {
                                                    'content-type': 'application/x-www-form-urlencoded'
                                                  },
                                                  success: function(res) {
                                                    if (res.data.code == 200) {
                                                      that.setData({
                                                        order: res.data.data.pageList
                                                      })
                                                      // 发送订阅通知
                                                      wx.request({
                                                        url: url + '/WeChatPayApi/toSendMessage',
                                                        data: {
                                                          orderId: options.currentTarget.dataset.orderid,
                                                          wxUserUuid: options.currentTarget.dataset.wxuseruuid
                                                        },
                                                        method: 'POST',
                                                        header: {
                                                          'content-type': 'application/x-www-form-urlencoded'
                                                        }
                                                      })

                                                      // 发送模板消息
                                                      wx.request({
                                                        url: url + '/WeChatPayApi/sendModelMms',
                                                        data: {
                                                          orderId: options.currentTarget.dataset.orderid,
                                                          wxUserUuid: options.currentTarget.dataset.wxuseruuid
                                                        },
                                                        method: 'POST',
                                                        header: {
                                                          'content-type': 'application/x-www-form-urlencoded'
                                                        }
                                                      })
                                                    } else {
                                                      wx.showToast({
                                                        title: res.data.msg,
                                                        icon: "none",
                                                        duration: 2000
                                                      })
                                                    }

                                                  },
                                                  fail: function(res) {
                                                    console.info('submit fail');
                                                  },
                                                  complete: function(res) {
                                                    console.info('submit complete');
                                                  }
                                                })

                                              } else {
                                                wx.showToast({
                                                  title: res.data.msg,
                                                  icon: "none",
                                                  duration: 2000
                                                })
                                              }
                                            }
                                          })
                                        } else {
                                          wx.showToast({
                                            title: res.data.msg,
                                            icon: "none",
                                            duration: 2000
                                          })
                                        }

                                      },
                                      fail: function(res) {
                                        console.info('submit fail');
                                      },
                                      complete: function(res) {
                                        console.info('submit complete');
                                      }
                                    })

                                  } else {
                                    wx.showToast({
                                      title: res.data.msg,
                                      icon: "none",
                                      duration: 2000
                                    })
                                  }
                                }
                              })

                            },
                            'fail': function(res) {
                              console.log("支付失败!");
                              console.log(res);
                            },
                            'complete': function(res) {
                              console.log("方法调用结束");
                              console.log(res);
                            }
                          })
                        } else {
                          wx.showToast({
                            title: res.data.msg,
                            icon: "none",
                            duration: 2000
                          })
                        }

                      },
                      fail: function(res) {
                        console.info('submit fail');
                      },
                      complete: function(res) {
                        console.info('submit complete');
                      }
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              }
            },
            fail: function(res) {
              console.info('submit fail');
            },
            complete: function(res) {
              console.info('submit complete');
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
          _that.setData({
            relationName: '',
            relationPhone: ''
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })



  },
  /**导航 */
  location: function(option) {
    let name = option.currentTarget.dataset.merchantname;
    let lat = option.currentTarget.dataset.lat;
    let lot = option.currentTarget.dataset.lot;
    let addr = option.currentTarget.dataset.address;
    console.log(lat);
    console.log(lot);
    //使用后台维护的腾讯服务经纬度(火星坐标系)
    wx.openLocation({
      longitude: Number(lot),
      latitude: Number(lat),
      name: name,
      address: addr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: "我的订单"
    })
    var that = this;
    //查询我的个人订单
    that.queryTable(pageNo, pageSize, app.globalData.openId, that.data.isTabOneInit, "N");
  },

  /**
   * 退订
   */
  unSubscribeOrder: function(option) {
    console.log(option);
    // 确定退订
    var that = this;
    var item = JSON.parse(that.data.item);
    let orderId = item.orderId;
    let cUuid = item.createUserName;
    let merchantId = item.merchantId;
    let totalFee = item.orderTotalPrice;
    let queryType = item.queryType;
    let isJielong = item.isJielong;
    let jielongPayOrderId = item.jielongPayOrderId;
    
    wx.request({
      url: url + '/WeChatPayApi/refund',
      data: {
        orderId: orderId,
        cUuid: cUuid,
        merchantId: merchantId,
        totalFee: totalFee,
        queryType: queryType,
        invoking: 0,
        isJielong: isJielong ? isJielong : "",
        jielongPayOrderId: jielongPayOrderId ? jielongPayOrderId : ""
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          Toast.success('退订成功!');
          if(that.data.tabActive == 0){
             //个人订单   重新加载列表
            pageNo = 1;
            that.queryTable(pageNo, pageSize, app.globalData.openId, false, "N");
          } else {
            //接龙订单
            jielongPageNo = 1;
            that.queryTable(jielongPageNo, jielongPageSize, app.globalData.openId, false, "Y");
          }
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },
  /**
   * 打电话
   */
  makeCall: function(option) {
    console.log(option);
    let item = option.currentTarget.dataset.item;
    if (!item.merchantPhone) {
      wx.showToast({
        title: "当前商家无联系方式",
        icon: "none",
        duration: 2000
      })
      return;
    }
    wx.makePhoneCall({
      phoneNumber: item.merchantPhone,
      success: function() {
        console.log("成功拨打电话")
      },
      fail: function() {
        console.log("拨打电话失败！")
      }
    })

  },
  /**
   * 查询订单
   */
  selectOrder: function(option) {
    var orderId = option.currentTarget.dataset.id;
    let queryType = option.currentTarget.dataset.querytype;
    let isShareByJielong = option.currentTarget.dataset.issharebyjielong;
    let jielongPayOrderId = option.currentTarget.dataset.jielongpayorderid;
    console.log(option);
    var that = this;
    wx.navigateTo({
      url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + queryType + "&isShareByJielong=" + isShareByJielong + "&jielongPayOrderId=" + jielongPayOrderId,
    })

    // wx.request({
    //   url: 'http://' + url + '/OrderApi/selectItem',
    //   data: {
    //     orderId: orderId
    //   },
    //   method: 'POST',
    //   header: {
    //     'content-type': 'application/x-www-form-urlencoded'
    //   },
    //   success: function(res) {
    //     if (res.data.code == 200) {
    //       var item = res.data.data;
    //       that.setData({
    //         itemInfoList: item
    //       });
    //       that.setData({
    //         selectOrderPopup: true
    //       });
    //     } else {
    //       wx.showToast({
    //         title: res.data.msg,
    //         icon: "none",
    //         duration: 2000
    //       })
    //     }
    //   },
    //   fail: function(res) {
    //     console.info('submit fail');
    //   },
    //   complete: function(res) {
    //     console.info('submit complete');
    //   }
    // })
  },
  onCloseSelect() {
    this.setData({
      selectOrderPopup: false
    });
  },
  onChange: function(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getTabBar().init();
    //查询我的个人订单
    // this.queryTable(pageNo, pageSize, app.globalData.openId, this.data.isTabOneInit, "N");
  },
  //列表搜索通用函数
  queryTable: function(pageNo, pageSize, openId, flag, isJielong) {
    var that = this;
    wx.request({
      url: url + '/OrderApi/listPageOrder',
      data: {
        pageNo: pageNo,
        pageSize: pageSize,
        createUserName: openId,
        isJielong: isJielong
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 200) {
          if (!flag) {
            if("N" == isJielong){
              //个人订单
              that.setData({
                order: res.data.data.pageList,
                isTabOneInit:true
              })
            } else {
              //接龙订单
              that.setData({
                jielongOrder: res.data.data.pageList,
                isTabTwoInit: true
              })
            } 
          } else {
            if (res.data.data.pageList.length > 0) {
              if ("N" == isJielong) {
                //个人订单
                that.setData({
                  order: that.data.order.concat(res.data.data.pageList)
                })
              } else {
                //接龙订单
                that.setData({
                  jielongOrder: that.data.order.concat(res.data.data.pageList)
                })
              }
              
            }
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },

  queryJielongOrder: function (pageNo, pageSize, openId, flag) {
    var that = this;
    wx.request({
      url: url + '/OrderApi/listPageJielongOrder',
      data: {
        pageNo: pageNo,
        pageSize: pageSize,
        createUserName: openId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          if (!flag) {
            that.setData({
              order: res.data.data.pageList
            })
          } else {
            if (res.data.data.pageList.length > 0) {
              that.setData({
                order: that.data.order.concat(res.data.data.pageList)
              })
            }
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    if(that.data.tabActive == 0){
      //个人订单
      pageNo = 1;
      that.queryTable(pageNo, pageSize, app.globalData.openId, false, "N");
    } else {
      //接龙订单
      jielongPageNo = 1;
      that.queryTable(jielongPageNo, jielongPageSize, app.globalData.openId, false, "Y");
    }  
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    if (that.data.tabActive == 0) {
      //个人订单
      pageNo = pageNo + 1;
      that.queryTable(pageNo, pageSize, app.globalData.openId, that.data.isTabOneInit, "N");
    } else {
      //接龙订单
      jielongPageNo = jielongPageNo + 1;
      that.queryTable(jielongPageNo, jielongPageSize, app.globalData.openId, that.data.isTabTwoInit, "Y");
    }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
  }
})